var config = require('./config'),
    http = require('http'),
    numCPUs = require('os').cpus().length,
    cp = require('child_process'),
    net = require('net');

//---------------------------------------------------------
var workers = [];
var createWorker = function(){
    var worker = cp.fork('ps_worker.js');

    //当接收到自杀信号的时候重启新的进程
    worker.on('message', function(message){
        if(message.act === 'suicide'){
            console.log('Worker : ' + worker.pid + ' suicide.');
            for(var i = 0; i < workers.length; i++){
                if(workers[i].pid == worker.pid){
                    workers.splice(i, 1);
                }
            }
            createWorker();
        }
    });

    //退出时重启新的进程
    worker.on('exit', function(){
        console.log('Worker ' + worker.pid + ' exited.');
        for(var i = 0; i < workers.length; i++){
            if(workers[i].pid == worker.pid){
                workers.splice(i, 1);
            }
        }
        createWorker();
    });

    //放入数组
    workers.push(worker);
    console.log('启动子进程:' + worker.pid);
};

//根据CPU数量创建子进程
for (var i = 0; i < numCPUs; i++) {
    createWorker();
}
//http服务
net.createServer(function (s) {
    s.pause();
    var worker = workers.shift();
    worker.send('c', s);
    workers.push(worker);
}).listen(config.port);

//---------------------------------------------------------
//web socket服务，其端口为http服务端口 + 1
var socket;
var createSocketIo = function(){
    socket = cp.fork('ps_socket.io.js');
    socket.on('message', function(message){
        if(message.act === 'suicide'){
            console.log('Socket ' + socket.pid + ' suicide.');
            socket = createSocketIo();
        }
    });
    //退出时重启新的进程
    socket.on('exit', function(){
        console.log('Socket ' + socket.pid + ' exited.');
        socket = createSocketIo();
    });
    console.log('启动子进程:' + socket.pid);
    return socket;
};

//创建web socket子进程
socket = createSocketIo();

//web socket服务
net.createServer(function (s) {
    s.pause();
    socket.send('c', s);
}).listen(config.port + 1);

//---------------------------------------------------------
//主进程关闭后关闭所有子进程
process.on('exit', function(){
    for(var i = 0; i < workers.length; i++){
        workers[i].kill();
    }
    socket.kill();
});
